//
//  TabbarItem.m
//  Budejie
//
//  Created by 远成物流 on 2017/5/12.
//  Copyright © 2017年 陈梦佳. All rights reserved.
//

#import "TabbarItem.h"
#import <SDAutoLayout/SDAutoLayout.h>

@interface TabbarItem ()

// + 按钮
@property(nonatomic,strong)UIButton *plusButton;

//上一次点击的button
@property(nonatomic,strong)UIControl *previousClickedTabbarButton;

@end

@implementation TabbarItem

-(UIButton *)plusButton{
    if (_plusButton == nil) {
        _plusButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_plusButton setImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];
        [_plusButton setImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateHighlighted];
        [_plusButton sizeToFit];
        [_plusButton addTarget:self action:@selector(plusBtnClicked) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_plusButton];
    }
    
    return _plusButton;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
    NSInteger count = self.items.count;
    
    CGFloat btnW = self.width_sd / (count+1);
    CGFloat btnH = self.height_sd;
    CGFloat btnX = 0;
    int i = 0;
    
    //遍历子控件调整位置
    for (UIControl *tabbarButton in self.subviews) {
        if ([tabbarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            
            if (i==0 && self.previousClickedTabbarButton == nil) {
                self.previousClickedTabbarButton = tabbarButton;
            }
            
            if (i == 2) {
                //加号按钮跳过
                i += 1;
            }
            
            btnX = i * btnW;
            
            tabbarButton.frame = CGRectMake(btnX, 0, btnW, btnH);
            
            i++;
            
            [tabbarButton addTarget:self action:@selector(tabbarButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    
    self.plusButton.center = CGPointMake(self.width_sd*0.5, self.height_sd*0.5);
}

//tabbar按钮点击监听
-(void)tabbarButtonClicked:(UIControl *)tabbarButton{
    if (tabbarButton == self.previousClickedTabbarButton) {
        //重复点击了
        [[NSNotificationCenter defaultCenter] postNotificationName:TabBarButtonDidRepeatClickedNotification object:nil];
    }
    
    self.previousClickedTabbarButton = tabbarButton;
}

//加号按钮点击
-(void)plusBtnClicked{
    if (self.plusButtonClicked) {
        self.plusButtonClicked();
    }
}

@end
